package com.yimi.yinhepda.utils;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.provider.Settings;
import android.widget.Toast;

import com.pda.uce.commom.util.LoadUtils;
import com.pda.uce.commom.util.MyDialog;
import com.pda.ym.utils.ActivityStack;
import com.pda.ym.utils.Constants;
import com.pda.ym.utils.DateHelper;
import com.pda.ym.utils.NetworkUtil;
import com.pda.ym.utils.SharedPreferUtil;
import com.pda.ym.utils.SoundVibratorManager;
import com.yimi.yinhepda.base.BaseApplication;
import com.yimi.yinhepda.R;
import com.pda.ym.callbacks.UICallBack;
import com.yimi.yinhepda.entity.response.QueryCheckTimeResponse;
import com.pda.ym.net.NetRequest;
import com.yimi.yinhepda.views.login.model.request.CheckTimeRequest;
import com.yimi.yinhepda.views.login.model.respones.CheckTimeResponse;
import com.yimi.yinhepda.views.setting_module.ServerSettingActivity;
import com.yimi.yinhepda.views.setting_module.SettingActivity;

import java.util.HashMap;
import java.util.Map;

/**
 * @author: lj
 * Date: 2019/8/14 11:36
 * Description:校验网络时间工具类
 */
public class CheckNetTimeUtil {

    /**
     * 每个界面发送广播时查询网络时间需要用到
     */
    public static void checkNetworkTime(Context context, String companyCode, String empCode, String pwd) {
        queryDictValue(context, companyCode, empCode, pwd, true, false, null);
    }

    /**
     * 装卸车扫描需要用到
     */
    public static void checkNetworkTime(Context context, String companyCode, String empCode, String pwd, boolean isAuto, UICallBack uiCallBack) {
        queryDictValue(context, companyCode, empCode, pwd, isAuto, false, uiCallBack);
    }

    /**
     * 登陆时需要用到，且不做时间校验开关
     */
    public static void checkNetworkTimeForLogin(Context context, String companyCode, String empCode, String pwd, UICallBack uiCallBack) {
        checkNetworkTime(context, companyCode, empCode, pwd, false, true, uiCallBack);
    }

    /**
     * 查询数据字典：时间校验开关 time_check
     */
    public static void queryDictValue(final Context context, final String companyCode, final String empCode,
                                      final String pwd, final boolean isAuto, final boolean isLogin, final UICallBack callBack) {
        if (SharedPreferUtil.getInstance().getOfflineMode()) {
            return;
        }
        if (isLogin) {
            //登录时必须校验网络时间
            checkNetworkTime(context, companyCode, empCode, pwd, isAuto, true, callBack);
        } else {
            Map<String, String> params = new HashMap<>(1);
            params.put("params", "time_check");
            new NetRequest().setMethod(NetRequest.Method.GET)
                    .setUrl(Constants.URL_QUERY_DICT_VALUE)
                    .setParams(params)
                    .setResponsClazz(QueryCheckTimeResponse.class)
                    .execute(new UICallBack() {
                        @Override
                        public void onError(String msg) {
                            if (context != null) {
                                Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
                            }
                            if (callBack != null) {
                                callBack.onError(msg);
                            }
                        }

                        @Override
                        public void onSuccess(Object obj) {
                            boolean hasCompCode = false;
                            QueryCheckTimeResponse response = (QueryCheckTimeResponse) obj;
                            if (response.getData() != null) {
                                Map<String, String> map = response.getData().getTimeCheck();
                                if (map != null) {
                                    for (String key : map.keySet()) {
                                        String value = map.get(key);
                                        String compCode = SharedPreferUtil.getInstance().getCompanyCode();
                                        if (value.equals(compCode)) {
                                            hasCompCode = true;
                                            break;
                                        }
                                    }
                                }
                            }
                            if (!hasCompCode) {
                                if (context != null) {
                                    //没有配置数据字典，则校验时间
                                    checkNetworkTime(context, companyCode, empCode, pwd, isAuto, false, callBack);
                                }
                            } else {
                                //有数据字典配置，不需要校验时间
                                if (callBack != null) {
                                    callBack.onSuccess(null);
                                }
                            }
                        }
                    });
        }
    }

    /**
     * 校验服务端时间
     */
    public static void checkNetworkTime(final Context context, final String companyCode, final String empCode,
                                        final String pwd, boolean isAuto, final boolean isLogin, final UICallBack callBack) {

        if (SharedPreferUtil.getInstance().getOfflineMode()) {
            return;
        }
        if (context == null) {
            return;
        }

        for (Activity activity : ActivityStack.getInstance().getActivities()) {
            if (activity instanceof SettingActivity || activity instanceof ServerSettingActivity) {
                return;
            }
        }

        //判断用户的设备时区是否为东八区
        if (!DateHelper.isInEasternEightZones()) {
            remindServerTimeCheckFailDialog(context, false, companyCode, empCode, pwd, "设备非中国时区，请修改！");
            return;
        }

        //校验网络时间与当前时间比较前后是否误差超过3分钟
        if (!NetworkUtil.isConnect(BaseApplication.getContext())) {
            Toast.makeText(context, "请检查网络连接！", Toast.LENGTH_LONG).show();
            return;
        }

        if ("".equals(empCode) && "".equals(pwd)) {
            //未登录，不校验服务器时间
            return;
        }

        if (!isAuto) {
            LoadUtils.showLoading("正在校验服务端时间...", context);
        }
        final String macAddress = NetworkUtil.getLocalMacAddressFromWifiInfo(context);
        CheckTimeRequest checkTimeRequest = new CheckTimeRequest(companyCode, empCode, pwd, macAddress);
        new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                .setResponsClazz(CheckTimeResponse.class)
                .setUrl(Constants.CHECK_TIME_URL)
                .setRequestObject(checkTimeRequest)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
                        if (callBack != null) {
                            callBack.onError(msg);
                        }
                    }

                    @Override
                    public void onError(String msg, Object obj) {
                        LoadUtils.hideLoading(context);
                        SoundVibratorManager.playSound(2);
                        if (isLogin) {
                            //登录时间校验错误处理
                            if (obj != null) {
                                if (obj instanceof CheckTimeResponse) {
                                    CheckTimeResponse response = (CheckTimeResponse) obj;
                                    if (!response.isSuccess()) {
                                        if (response.getErrorMessages() == null) {
                                            remindGetServereTimeFailDialog(context, "", "账号或者密码错误！");
                                            return;
                                        }
                                    }
                                }
                                remindGetServereTimeFailDialog(context, msg, "");
                            } else {
                                remindGetServereTimeFailDialog(context, msg, "");
                            }
                        } else {
                            remindServerTimeCheckFailDialog(context, true, companyCode, empCode, pwd, null);
                        }
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        LoadUtils.hideLoading(context);
                        if (obj instanceof CheckTimeResponse) {
                            CheckTimeResponse checkTimeResponse = (CheckTimeResponse) obj;
                            //获取时间戳
                            Long serverTime = checkTimeResponse.getData();
                            //获取当前时间戳
                            Long clientTime = DateHelper.getTimeStamp();
                            Long checkTime = clientTime - serverTime;
                            if (Math.abs(checkTime) > (180 * 1000)) {
                                //客户端时间和服务端时间比较前后相差超出3分钟，则提示用户校验失败，是否重试
                                remindServerTimeCheckFailDialog(context, false, companyCode, empCode, pwd, "本机时间与网络时间不同步，是否设置时间？");
                            } else {
                                if (callBack != null) {
                                    callBack.onSuccess(null);
                                }
                            }
                        }
                    }
                });
    }

    /**
     * 网络时间校验获取失败提示框
     */
    public static void remindGetServereTimeFailDialog(Context context, String msg, String msg2) {
        if (context instanceof Activity && ((Activity) context).isFinishing()) {
            return;
        }
        MyDialog dialog = MyDialog.getInstance(context);
        dialog.setIcon(R.drawable.alert);
        dialog.setDialogType(MyDialog.DialogType.ALERT_DIALOG);
        dialog.setTitle("系统提示");
        if (msg2 != null && !"".equals(msg2)) {
            dialog.setMessage(msg2);
        } else {
            dialog.setMessage("网络时间获取失败：" + msg);
        }
        dialog.setPositiveClickListener("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                MyDialog.setNull();
            }
        });
        try {
            dialog.show();
        } catch (Exception e) {
            e.printStackTrace();
            MyDialog.setNull();
        }
    }

    /**
     * 客户端时间和服务端时间比较前后相差超出3分钟，则提示用户校验失败，是否重试
     */
    public static void remindServerTimeCheckFailDialog(final Context context, boolean isRetry, final String companyCode,
                                                       final String empCode, final String pwd, String message) {
        if (context instanceof Activity && ((Activity) context).isFinishing()) {
            return;
        }
        //设置该标志，不返回扫描结果
        MyDialog.setTag(1);
        MyDialog dialog = MyDialog.getInstance(context);
        //时间校验提示标志
        dialog.setIcon(R.drawable.alert);
        dialog.setDialogType(MyDialog.DialogType.ALERT_DIALOG);
        dialog.setTitle("系统提示");
        if (isRetry) {
            dialog.setMessage("网络时间获取失败，是否重试？");
            dialog.setPositiveClickListener("是", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    MyDialog.setNull();
                    checkNetworkTime(context, companyCode, empCode, pwd);
                }
            });
        } else {
            dialog.setMessage(message);
            dialog.setPositiveClickListener("是", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    MyDialog.setNull();
                    Intent intent = new Intent(Settings.ACTION_DATE_SETTINGS);
                    context.startActivity(intent);
                }
            });
        }
        dialog.setNegativeClickListener(R.drawable.btn_login_selector, "退出", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //开启扫描
                dialog.dismiss();
                MyDialog.setNull();
                ActivityStack.getInstance().exit();
            }
        });
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);
        try {
            dialog.show();
        } catch (Exception e) {
            e.printStackTrace();
            MyDialog.setNull();
        }
    }
}
